use anyhow::Result;
use serialport::{self, SerialPort};
use std::time::Duration;

const BAUDRATE: u32 = 115_200;

pub struct DevRCIOS {
    pub port: Box<dyn SerialPort>,
}

#[derive(Clone, Debug, Default)]
pub struct R2KResult {
    pub r2ktype: String,
    pub content: Vec<u8>,
}

impl DevRCIOS {
    pub fn open(port_name: String) -> Result<Box<dyn SerialPort>> {
        let wait_time = Duration::from_millis(5);
        let port_build = serialport::new(port_name, BAUDRATE);
        let port: Box<dyn SerialPort> = port_build.timeout(wait_time).open()?;
        Ok(port)
    }

    pub fn init(port_name: String) -> Result<Self> {
        let result = DevRCIOS {
            port: DevRCIOS::open(port_name)?,
        };
        Ok(result)
    }
}
